<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120"
    >
      <el-form-item label="审批状态" prop="approvalState">
        <el-select clearable v-model="formData.approvalState" placeholder="请选择" class="!w-200px">
          <el-option
            v-for="dict in getIntDictOptionsFn(dict_type.BID_APPROVAL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="approvalRemark">
        <el-input :maxlength="100" v-model="formData.approvalRemark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as approval from '@/api/approval'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const dict_type = ref(DICT_TYPE)
const getIntDictOptionsFn = ref(getIntDictOptions)
const emit = defineEmits(['success'])
const formRef = ref()
const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData: Record<string, any> = ref({
  id: undefined,
  approvalState: undefined,
  approvalRemark: undefined
})
const formRules = reactive({
  approvalState: [{ required: true, message: '审批状态不能为空', trigger: 'change' }]
})

const open = async (id: number) => {
  resetFn()
  dialogVisible.value = true
  dialogTitle.value = '审批'
  formData.value.id = id
}

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    await approval.approvalAccount(formData.value)
    message.success(t('common.operateSuccess'))
    dialogVisible.value = false
    resetFn()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetFn = () => {
  formData.value = {
    id: undefined,
    approvalState: undefined,
    approvalRemark: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
